package logic

import (
	"context"
	"select/models/mysql"

	"select/selectrpc/internal/svc"
	"select/selectrpc/selectrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopAddLogic {
	return &ShopAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopAddLogic) ShopAdd(in *selectrpc.ShopAddRequest) (*selectrpc.ShopAddResponse, error) {
	// todo: add your logic here and delete this line
	begin := mysql.DB.Debug().Begin()
	var class mysql.Class
	begin.Where("name=?", in.Name).Find(&class)
	if class.ID == 0 {
		class = mysql.Class{

			Name: in.Name,
		}
		err := mysql.DB.Debug().Create(&class).Error
		if err != nil {
			return nil, err
			begin.Rollback()
		}
	}
	var brand mysql.Brand
	begin.Where("name=?", in.Name).Find(&brand)
	if brand.ID == 0 {
		brand = mysql.Brand{

			Name: in.Name,
		}
		err := mysql.DB.Debug().Create(&brand).Error
		if err != nil {
			return nil, err
			begin.Rollback()
		}
	}
	shop := mysql.Shop{

		Name:    in.Name,
		Price:   float64(in.Price),
		ClassId: in.ClassId,
		BrandId: in.BrandId,
	}
	mysql.DB.Debug().Where("name=?", in.Name).Where("%+name+%").Find(&shop)
	err := begin.Create(&shop).Error
	if err != nil {
		return nil, err
		begin.Rollback()
	}
	begin.Commit()
	return &selectrpc.ShopAddResponse{
		ShopId: int64(shop.ID),
	}, nil
}
